import Vue from 'vue'
import Vuex from 'vuex'
import dayjs from "dayjs"
import storage from "@/utils/storage.js"
import {
	getUserInfo
} from "@/api/my";
import {
	ListDevice,
	IndexHistoryData
} from "@/api/device.js";
import {
	getOneMessage
} from "@/api/message.js";
import {
	ByStepToDistance
} from "@/utils/filter.js"
import {
	PICTURE_URL
} from "@/utils/config.js"
import {
	UpdateCid
} from "@/api/login.js"
import {
	getSleepGroupList
} from "@/api/analyse";
import {
	InitBlueTooth,
	CreateBlueToothConnection
} from "@/utils/BLE.js";


const ServerUUID = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
const CharacteristicsNotify = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
const CharacteristicsWrite = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		userinfo: {},
		pictureUrl: PICTURE_URL,
		blueDevice: '', // 蓝牙搜索的设备列表
		appDevice: [], // 我们平台的设备列表
		blueAvailable: false, // 蓝牙适配器是否可用,蓝牙是否打开 默认离线
		searchState: false, // 是否蓝牙正在搜索
		currentLinkDevice: '', // 当前连接的蓝牙设备列表
		deviceAvailable: '', // 蓝牙适配器是否可用,蓝牙是否打开
		blueElectric: '', // 蓝牙电量
		blueBodyInfo: {
			xinlv: '',
			xueyang: '',
			gaoya: '',
			diya: '',
			step: '', // 计步
			juli: '', // 距离
			kcal: '',
			houe: '',
			minute: ''
		},
		stepCounting: { //计步运动
			state: '', // 空计步 start开始计步 end 结束计步
			startStep: '', // 开始步数
			endStep: '', // 结束步数
			startJuli: '', // 开始步数
			endJuli: '', // 结束步数
			startKcal: '', // 开始步数
			endKcal: '', // 结束步数
			startTime: '', // 开始步数
			endTime: '' // 结束步数
		}
	},
	getters: {
		UserInfo: (state) => {
			return state.userinfo
		},
		PictureUrl: (state) => {
			return state.pictureUrl
		},
		BlueDevice: (state) => {
			return state.blueDevice
		},
		AppDevice: (state) => {
			return state.appDevice
		},
		BlueAvailable: (state) => {
			return state.blueAvailable
		},
		SearchState: (state) => {
			return state.searchState
		},
		CurrentLinkDevice: (state) => {
			return state.currentLinkDevice
		},
		DeviceAvailable: (state) => {
			return state.deviceAvailable
		},
		BlueElectric: (state) => {
			return state.blueElectric
		},
		BlueBodyInfo: (state) => {
			return state.blueBodyInfo
		},
		StepCounting: (state) => {
			return state.stepCounting
		},
	},
	mutations: {
		SetUserInfo(state, params) {
			console.log("--SetUserInfo", params)
			state.userinfo = params
		},
		SetBlueDevice(state, params) {
			console.log("--SetBlueDevice", params)
			state.blueDevice = params
		},
		SetAppDevice(state, params) {
			console.log("--SetAppDevice", params)
			state.appDevice = params
		},
		SetBlueAvailable(state, params) {
			console.log("--SetBlueAvailable", params)
			state.blueAvailable = params
		},
		SetSearchState(state, params) {
			console.log("--SetSearchState", params)
			state.searchState = params
		},
		SetCurrentLinkDevice(state, params) {
			console.log("--SetCurrentLinkDevice", params)
			state.currentLinkDevice = params
		},
		SetDeviceAvailable(state, params) {
			console.log("--SetDeviceAvailable", params)
			state.deviceAvailable = params
		},
		SetBlueElectric(state, params) {
			state.blueElectric = params
		},
		SetBlueBodyInfo(state, params) {
			console.log("--SetBlueBodyInfo", params)
			state.blueBodyInfo = params
		},
		SetStepCounting(state, params) {
			console.log(1, params)
			if (params.startStep) {
				params.startJuli = ByStepToDistance(params.startStep)
				console.log(1, params.startJuli)
			}
			console.log(1)
			if (params.endStep) {
				console.log(1)
				params.endJuli = ByStepToDistance(params.endStep)
				console.log(1)
			}
			console.log(1)
			console.log("--SetStepCounting", JSON.stringify({
				...state.stepCounting,
				...params
			}))
			state.stepCounting = {
				...state.stepCounting,
				...params
			}
		}
	},
	actions: {
		/**
		 * 清除用户基本信息
		 */
		ClearUserinfo({
			commit,
			state,
			dispatch
		}, params) {
			storage.removeCurrentDevice()
			storage.removeUserInfo();
			storage.removeToken();
			commit("SetUserInfo", {})
			dispatch("SetupCurrentDeviceState", "")
			commit('SetBlueBodyInfo', {
				xinlv: '',
				xueyang: '',
				gaoya: '',
				diya: '',
				step: '', // 计步
				juli: '', // 距离
				kcal: '',
				houe: '',
				minute: ''
			})
		},
		/**
		 * 存放用户基本信息
		 * 判断用户等级和完善信息情况
		 */
		ActionUserList({
			dispatch,
			commit,
			state
		}, params) {
			console.log("--ActionUserList", params)
			if (params.type === 'login') {
				storage.setToken(params.token);
				storage.setUserInfo(params.user)
				commit("SetUserInfo", params.user)
				console.log(params)
				if (params.utype === 1) {
					// 二级用户
					uni.$emit("LOGIN")
					uni.switchTab({
						url: "/pages/index/index",
					});
					// #ifdef APP-PLUS
					dispatch("UniPush")
					// #endif
				} else {
					// 一级用户
					if (params.user.uname) {
						// 信息已经完善
						uni.$emit("LOGIN")
						uni.switchTab({
							url: "/pages/index/index",
						});
						storage.setUserInfo(params.user)
						// #ifdef APP-PLUS
						dispatch("UniPush")
						// #endif
					} else {
						uni.redirectTo({
							url: "/pages/moduleLogin/info/info?back=0&phone=" + params.user.uphone,
						});
					}
				}
			} else {
				commit("SetUserInfo", params)
			}
		},
		/**
		 * 个推
		 */
		UniPush({
			commit,
			state
		}, params) {
			console.log('--actionUniPush', params)
			plus.push.getClientInfoAsync((info) => {
				let cid = info["clientid"];
				UpdateCid({
					cid: cid
				}).then((res) => {
					console.log('---------------个推', cid, res)
				})
			});
		},
		/**
		 * 搜索蓝牙设备
		 */
		SearchAndGetBlueToothList({
			commit,
			state,
			dispatch
		}, params) {
			if (state.searchState) return
			return new Promise((resolve, reject) => {
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						commit('SetBlueDevice', '')
						commit('SetSearchState', true)
						// 获取设备列表
						uni.onBluetoothDeviceFound((res) => {
							var bluetoothArr = res.devices.filter(function(
								obj) {
								return obj.name != ""
							})
							bluetoothArr = bluetoothArr.map((item) => {
								item.state = "no"
								return item
							})
							if (bluetoothArr.length === 0) return
							if (state.blueDevice === '') {
								dispatch('ActionBuleList', bluetoothArr)
							} else {
								let filterArr = state.blueDevice.filter((item) => {
									return item.deviceId === bluetoothArr[0]
										.deviceId
								})
								if (filterArr.length === 0) {
									dispatch('ActionBuleList', [...state.blueDevice,
										...bluetoothArr
									])
								}
							}
						})
						setTimeout(() => {
							uni.stopBluetoothDevicesDiscovery({
								success(res) {
									console.log('停止搜索蓝牙', res)
									if (state.blueDevice.length === 0) {
										commit("SetBlueDevice", [])
									}
									commit('SetSearchState', false)
									resolve()
								}
							})
						}, 8000)
					},
					fail: (err) => {
						reject(err)
						console.log(err)
					}
				})
			})
		},

		/**
		 * 存放蓝牙设备列表
		 * 蓝牙设备和app设备对比 更新双方状态
		 */
		ActionBuleList({
			commit,
			state
		}, params) {
			if (params === '') {
				commit('SetBlueDevice', '')
			} else {
				let blueList = params
				let appList = state.appDevice
				let currentLink = state.currentLinkDevice
				blueList = blueList.map((blue) => {
					let bid = blue.deviceId
					appList.map((app) => {
						if (app.deviceId === bid) {
							blue.nickName = app.nickName
						}
					})
					if (bid === currentLink.deviceId) {
						blue.state = currentLink.state
					}
					return blue
				})
				commit('SetBlueDevice', blueList)
			}
		},
		/**
		 * 蓝牙列表，修改蓝牙列表的连接状态
		 */
		ActionDeviceLink({
			commit,
			state
		}, params) {
			let list = state.blueDevice.map((item) => {
				if (item.deviceId === params.deviceId) {
					item.state = params.type
				} else {
					item.state = 'no'

				}
				return item
			})
			console.log('ActionDeviceLink', params, list)
			commit('SetBlueDevice', list)
		},
		/**
		 * 1.设置当前连接的设备
		 * 2.更新APP设备列表中的连接状态
		 * 3.蓝牙列表，修改蓝牙列表的连接状态
		 */
		ActionCurrentLink({
			commit,
			state
		}, param) {
			let params = param || {}
			let appDevice = state.appDevice
			let blueDevice = state.blueDevice
			if (appDevice && appDevice.length > 0 && params) {
				appDevice = appDevice.map((item) => {
					if (item.deviceId === params.deviceId) {
						item.state = params.state
						params.nickName = item.nickName
					} else {
						item.state = 'no'

					}
					return item
				})
			}
			if (blueDevice && blueDevice.length > 0 && params) {
				blueDevice = blueDevice.map((item) => {
					if (item.deviceId === params.deviceId) {
						item.state = params.state
						item.nickName = params.nickName
					} else {
						item.state = 'no'
					}
					if (param === '') {
						console.log('...............')
						item.nickName = ''
					}
					return item

				})
			}
			// 如果设置当前连接设备为离线状态  则清空数据
			if (params.state === 'no') {
				commit("SetBlueElectric", '')
				commit("SetBlueBodyInfo", {
					xinlv: '',
					xueyang: '',
					gaoya: '',
					diya: '',
					step: '',
					kcal: '',
				})
			}
			commit('SetCurrentLinkDevice', param)
			commit('SetBlueDevice', blueDevice)
			commit('SetAppDevice', appDevice)
		},
		/**
		 * 设置当前设备（带当前设备状态）
		 * 如果是‘’  则是清除当前设备缓存，包含section和vuex
		 */
		SetupCurrentDeviceState({
			dispatch,
			commit,
			state
		}, params) {
			if (params === '') {
				storage.removeCurrentDevice()
			} else {
				storage.setCurrentDevice(params)
				dispatch("ActionGetOneMessage", params)
			}
			dispatch("ActionCurrentLink", params)
			if (params.state === 'link') {
				dispatch('SleepBlueInfo', params)
				if (state.userinfo.utype === 1) {
					dispatch('TwoIndexHistory', params)
				}
			}
		},
		// 二级用户获取一级用户设备的最新数据
		ActionGetOneMessage({
			dispatch,
			commit,
			state
		}, params) {
			getOneMessage({
				deviceId: params.deviceId
			}).then((res) => {
				let info = res.data.data
				dispatch("ActionBlueBodyInfo", info)
			})
		},
		/**
		 * 从蓝牙获取数据的
		 * 心率 血压 步数 ...
		 */
		ActionBlueBodyInfo({
			commit,
			state
		}, params) {
			if (!params) return
			let info = {
				...state.blueBodyInfo,
				...params
			}
			if (!!params.step || params.step === '0') {
				info.juli = ByStepToDistance(params.step)
			}
			if (params.deepminute !== undefined) {
				let houe = parseFloat(params.shallowhoue) + parseFloat(params.deephoue)
				let minute = parseFloat(params.shallowminute) + parseFloat(params.deepminute)
				if (minute > 60) {
					houe = houe + 1
					minute = minute - 60
				}
				info.houe = houe
				info.minute = minute
			}
			console.log("--ActionUserList", info)
			commit('SetBlueBodyInfo', info)
		},
		/**
		 * 获取APP设备列表
		 */
		ActionDeviceList({
			commit,
			state,
		}) {
			return new Promise((resolve, reject) => {
				commit('SetAppDevice', [])
				ListDevice({
					delFlag: 0
				}).then(res => {
					let data = res.data.rows
					let device = state.currentLinkDevice
					if (device) {
						data = data.map((item) => {
							if (item.deviceId === device.deviceId) {
								device.nickName = item.nickName
								item.state = device.state
							}
							return item
						})
					}
					commit('SetCurrentLinkDevice', device)
					commit('SetAppDevice', data)
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		},
		/**
		 * 1.设置当前连接的电量
		 * 2.更新APP设备列表中电量
		 */
		ActionElectric({
			commit,
			state
		}, params) {
			let appDevice = state.appDevice
			console.log('appDevice', appDevice)
			if (appDevice && appDevice.length > 0) {
				appDevice = appDevice.map((item) => {
					if (item.deviceId === params.deviceId) {
						item.electric = params.percent
					}
					return item
				})
			}
			commit('SetBlueBodyInfo', {
				...state.blueBodyInfo,
				...params
			})
			commit('SetAppDevice', appDevice)
		},
		SetUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getUserInfo().then(res => {
					let data = res.data.data
					console.log(data)
					storage.setUserInfo(data);
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		/**
		 * 获取睡眠数据
		 */
		SleepBlueInfo({
			commit,
			dispatch
		}, params) {
			getSleepGroupList({
				type: 'day',
				deviceId: params.deviceId,
			}).then((res) => {
				let sleepobj = res.data.data.data
				console.log('......................', res.data.data.data)
				if (sleepobj.shallowhoue !== null) {
					dispatch("ActionBlueBodyInfo", {
						shallowhoue: sleepobj.shallowhoue,
						shallowminute: sleepobj.shallowminute,
						deephoue: sleepobj.deephoue,
						deepminute: sleepobj.deepminute,
					})
				}
			})
		},
		/**
		 * 获取二级用户首页历史数据
		 */
		TwoIndexHistory({
			commit,
			dispatch
		}, params) {
			IndexHistoryData({
				deviceId: params.deviceId,
			}).then((res) => {
				let sleepobj = res.data.data
				if (sleepobj.shallowhoue !== null) {
					dispatch("ActionBlueBodyInfo", {
						shallowhoue: sleepobj.shallowhoue,
						shallowminute: sleepobj.shallowminute,
						deephoue: sleepobj.deephoue,
						deepminute: sleepobj.deepminute,
						xinlv: sleepobj.xinlv,
						xueyang: sleepobj.xueyang,
						step: sleepobj.step,
						gaoya: sleepobj.shuzhangya,
						diya: sleepobj.shousuoya,
						kcal: sleepobj.kcal
					})
				}
			})
		},
		/**
		 * 给手环发送指令
		 */
		WriteBlueTooth({
			commit,
			dispatch
		}, type) {
			let device = storage.getCurrentDevice()
			if (!device) {
				uni.showToast({
					title: "未连接设备",
					icon: "none",
					duration: 3000
				})
				return
			}
			if (device.state !== 'link') {
				uni.showToast({
					title: "该设备未连接",
					icon: "none",
					duration: 3000
				})
				return
			}
			console.log('WriteBlueTooth', type, device)
			if (type === 'time') {
				var buffer2 = new ArrayBuffer(14)
				var dw2 = new DataView(buffer2)
				dw2.setUint8(0, 0xab)
				dw2.setUint8(1, 0x00)
				dw2.setUint8(2, 0x0b)
				dw2.setUint8(3, 0xff)
				dw2.setUint8(4, 0x93)
				dw2.setUint8(5, 0x80)
				dw2.setUint8(6, 0x00)
				dw2.setUint8(7, 0x07)
				dw2.setUint8(8, 0xE6)
				let today = dayjs()
				let month = (today.month() + 1).toString(16)
				let day = (today.date()).toString(16)
				let hour = (today.hour()).toString(16)
				let minute = (today.minute()).toString(16)
				let second = (today.second()).toString(16)
				console.log(month, day, hour, minute, second)
				if (month.length === 1) month = '0' + month
				if (day.length === 1) day = '0' + day
				if (hour.length === 1) hour = '0' + hour
				if (minute.length === 1) minute = '0' + minute
				if (second.length === 1) second = '0' + second
				dw2.setUint8(9, parseInt(month, 16))
				dw2.setUint8(10, parseInt(day, 16))
				dw2.setUint8(11, parseInt(hour, 16))
				dw2.setUint8(12, parseInt(minute, 16))
				dw2.setUint8(13, parseInt(second, 16))
				uni.writeBLECharacteristicValue({
					...device,
					characteristicId: CharacteristicsWrite,
					value: buffer2,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res)
					}
				})
			}
			if (type === 'electric') {
				console.log('333-electric')
				var buffer = new ArrayBuffer(12)
				var dw = new DataView(buffer)
				dw.setUint8(0, 0xab)
				dw.setUint8(1, 0x00)
				dw.setUint8(2, 0x09)
				dw.setUint8(3, 0xff)
				dw.setUint8(4, 0x91)
				dw.setUint8(5, 0x80)
				dw.setUint8(6, 0x00)
				dw.setUint8(7, 0x00)
				dw.setUint8(8, 0x00)
				dw.setUint8(9, 0x00)
				dw.setUint8(10, 0x00)
				dw.setUint8(11, 0x00)
				uni.writeBLECharacteristicValue({
					...device,
					characteristicId: CharacteristicsWrite,
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res)
					}
				})
			}
			if (type === 'tongbu') {
				console.log('tongbu')
				var buffer = new ArrayBuffer(10)
				var dw2 = new DataView(buffer)
				dw2.setUint8(0, 0xab)
				dw2.setUint8(1, 0x00)
				dw2.setUint8(2, 0x07)
				dw2.setUint8(3, 0xff)
				dw2.setUint8(4, 0x52)
				dw2.setUint8(5, 0x80)
				dw2.setUint8(6, 0x00)
				dw2.setUint8(7, 0x16)
				dw2.setUint8(8, 0x06)
				dw2.setUint8(9, 0x0d)
				let today = dayjs().subtract(1, 'day')
				let month = (today.month() + 1).toString(16)
				let day = (today.date()).toString(16)
				if (month.length === 1) month = '0' + month
				if (day.length === 1) day = '0' + day
				dw2.setUint8(8, parseInt(month, 16))
				dw2.setUint8(9, parseInt(day, 16))
				console.log('@@@@@写的设备@@@@@@@', device.deviceId, {
					...device,
					characteristicId: CharacteristicsWrite,
				})
				uni.writeBLECharacteristicValue({
					...device,
					characteristicId: CharacteristicsWrite,
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res)
					}
				})
				setTimeout(() => {
					var buffer2 = new ArrayBuffer(12)
					var dw = new DataView(buffer2)
					dw.setUint8(0, 0xab)
					dw.setUint8(1, 0x00)
					dw.setUint8(2, 0x09)
					dw.setUint8(3, 0xff)
					dw.setUint8(4, 0x51)
					dw.setUint8(5, 0x08)
					dw.setUint8(6, 0x00)
					dw.setUint8(7, 0x00)
					dw.setUint8(8, 0x00)
					dw.setUint8(9, 0x00)
					dw.setUint8(10, 0x00)
					dw.setUint8(11, 0x00)
					uni.writeBLECharacteristicValue({
						...device,
						characteristicId: CharacteristicsWrite,
						value: buffer2,
						success(res) {
							console.log('writeBLECharacteristicValue success', res.errMsg)
						},
						fail(res) {
							console.log('writeBLECharacteristicValue fail', res)
						}
					})
				}, 500)
			}
			if (type === "test") {
				console.log('test')
				var buffer = new ArrayBuffer(12)
				var dw = new DataView(buffer)
				dw.setUint8(0, 0xab)
				dw.setUint8(1, 0x00)
				dw.setUint8(2, 0x09)
				dw.setUint8(3, 0xff)
				dw.setUint8(4, 0x32)
				dw.setUint8(5, 0x80)
				dw.setUint8(6, 0x01)
				dw.setUint8(7, 0x00)
				dw.setUint8(8, 0x00)
				dw.setUint8(9, 0x00)
				dw.setUint8(10, 0x00)
				dw.setUint8(11, 0x00)
				uni.writeBLECharacteristicValue({
					...device,
					characteristicId: CharacteristicsWrite,
					value: buffer,
					success(res) {
						dispatch("ActionBlueBodyInfo", {
							test: 'ing'
						})
						console.log('writeBLECharacteristicValue success', res.errMsg)
						setTimeout(() => {
							var buffer2 = new ArrayBuffer(12)
							var dw2 = new DataView(buffer2)
							dw2.setUint8(0, 0xab)
							dw2.setUint8(1, 0x00)
							dw2.setUint8(2, 0x09)
							dw2.setUint8(3, 0xff)
							dw2.setUint8(4, 0x32)
							dw2.setUint8(5, 0x80)
							dw2.setUint8(6, 0x00)
							dw2.setUint8(7, 0x00)
							dw2.setUint8(8, 0x00)
							dw2.setUint8(9, 0x00)
							dw2.setUint8(10, 0x00)
							dw2.setUint8(11, 0x00)
							uni.writeBLECharacteristicValue({
								...device,
								characteristicId: CharacteristicsWrite,
								value: buffer2,
								success(res) {
									console.log('writeBLECharacteristicValue success',
										res.errMsg)
								},
								fail(res) {
									uni.showToast({
										title: "测量失败,即将重新连接设备",
										icon: "none",
										duration: 3000
										
									})
									uni.$emit("LOGIN")
									dispatch("ActionBlueBodyInfo", {
										test: 'finish'
									})
									console.log('writeBLECharacteristicValue fail', res)
								}
							})
						}, 60000)
					},
					fail(res) {
						uni.showToast({
							title: "一键测量指令发送失败,即将重新连接设备",
							icon: "none",
							duration: 3000
						})
						uni.$emit("LOGIN")
						console.log('writeBLECharacteristicValue fail', res)
					}
				})

			}
			// 基本信息  手环型号，主板号
			if (type === 'baseinfo') {
				console.log('333-baseinfo')
				var buffer = new ArrayBuffer(12)
				var dw = new DataView(buffer)
				dw.setUint8(0, 0xab)
				dw.setUint8(1, 0x00)
				dw.setUint8(2, 0x09)
				dw.setUint8(3, 0xff)
				dw.setUint8(4, 0x92)
				dw.setUint8(5, 0x80)
				dw.setUint8(6, 0x01)
				dw.setUint8(7, 0x00)
				dw.setUint8(8, 0x00)
				dw.setUint8(9, 0x00)
				dw.setUint8(10, 0x00)
				dw.setUint8(11, 0x00)
				uni.writeBLECharacteristicValue({
					...device,
					characteristicId: CharacteristicsWrite,
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res)
					}
				})
			}
		},
		loginOut({
			commit
		}) {

		}
	}
})
export default store
